#define  _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* getIntersectionNode(struct ListNode* headA, struct ListNode* headB) {
    if (headA == NULL || headB == NULL)
    {
        return NULL;
    }
    int count1 = 0;
    int count2 = 0;
    struct ListNode* cur1 = headA, * c1 = headA;
    struct ListNode* cur2 = headB, * c2 = headB;
    while (cur1)
    {
        count1++;
        cur1 = cur1->next;
    }
    while (cur2)
    {
        count2++;
        cur2 = cur2->next;
    }


    int gap = 0;
    if (cur1 == cur2)
    {
        if (count1 > count2)
        {
            gap = count1 - count2;
            while (gap--)
            {
                c1 = c1->next;
            }
            while (c1 != c2)
            {
                c1 = c1->next;
                c2 = c2->next;
            }
            return c1;
        }
        else
        {
            gap = count2 - count1;
            while (gap--)
            {
                c2 = c2->next;
            }
            while (c1 != c2)
            {
                c1 = c1->next;
                c2 = c2->next;
            }
            return c1;
        }
    }
    return NULL;

}